package withouther.system.plugins.monitor.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import withouther.system.core.base.BaseServiceImpl;
import withouther.system.core.util.StringUtils;
import withouther.system.core.util.page.PageQuery;
import withouther.system.core.util.page.PageUtils;

import withouther.system.plugins.monitor.entity.Log;
import withouther.system.plugins.monitor.mapper.LogMapper;
import withouther.system.plugins.monitor.service.LogService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@Service("LogService")
public class LogServiceImpl extends BaseServiceImpl<LogMapper, Log> implements LogService {

    @Resource(name = "asyncExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<Log> page = this.page(
                new PageQuery<Log>().getPage(params),
                new QueryWrapper<Log>()
                .eq(ObjectUtil.isNotNull(params.get("logType")), "log_type", params.get("logType"))
        );
        return new PageUtils(page);
    }

    @Override
    public void save(HttpServletRequest request, JoinPoint join, Log log) {
        threadPoolTaskExecutor.submit(() -> {
            try {
                log.setDescription(getAnnotationLog(join).value());
                log.setAddress(request.getRequestURI());
                log.setRequestIp(StringUtils.getIp(request));
                log.setBrowser(StringUtils.getBrowser(request));
                Map<String, String[]> map = ServletUtil.getParams(request);
                String params = JSON.toJSONString(map);
                log.setParams(params);
                this.save(log);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private withouther.system.core.aop.log.Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(withouther.system.core.aop.log.Log.class);
        }
        return null;
    }

}